#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'tyh'
__mtime__ = '18-10-10'
# code is far away from bugs with the god animal protecting ~
"""
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

import constants


def generate_save_user_token(openid):
    ''' 使用itdangerous 加密 openid 以便发送给前端 '''
    tjs = TJS(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
    data = {'openid': openid}

    return tjs.dumps(data).decode()

def check_save_user_token(access_token):
    """
    检验保存用户数据的token
    :param token: token
    :return: openid or None
    """
    serializer = TJS(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
    try:
        data = serializer.loads(access_token)
    except Exception as e:
        return None
    else:
        return data